package com.wy.scs.rabbitmq.producerd.controller;

import com.alibaba.fastjson.JSON;
import com.wy.scs.rabbitmq.producerd.message.MessageData;
import com.wy.scs.rabbitmq.producerd.message.MySource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author wangyong
 */
@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private MySource mySource;

    @GetMapping("/send_batch")
    public boolean sendBatch() throws InterruptedException {
        // 发送 3 条消息，每条中间间隔 10 秒
        for (int i = 0; i < 3; i++) {
            // 创建 Message
            MessageData message = new MessageData();
            message.setId(new Random().nextInt());
            // 创建 Spring Message 对象
            Message<String> springMessage = MessageBuilder.withPayload(JSON.toJSONString(message))
                    .build();
            // 发送消息
            mySource.demoOutput().send(springMessage);

            // 故意每条消息之间，隔离 10 秒
            log.info("批量发送消息：发送编号：{} 发送成功", message.getId());
            Thread.sleep(10 * 1000L);
        }
        return true;
    }

}
